#!/usr/bin/python3

#Path config
import os,sys
import urllib.parse
from Bishop_web import bottle

AppPath=''
Platform=sys.platform
def envadd():
    global AppPath
    path=os.path.dirname(__file__)
    path1=os.path.split(path)[0]
    sys.path.append(path1)
    AppPath=path
    path2=os.path.split(path1)[0]
    sys.path.append(path2)
    for i in os.listdir(path2):
        sys.path.append((os.path.join(path2,i)))
envadd()


#IMPORTS
from bottle import run,redirect,TEMPLATE_PATH,template,Bottle, static_file,request, view,response,SimpleTemplate
from models import Registr_login,Cheklogin,GetIdUser,ChekNewsForLogin, \
SetNewsForLogin,GetContentPage,SetContentPage,NewsControlerforAdmin,GetNewsOnsite,\
AddBugreport,GetBugsTopics,GetTopicOfBugreport,AddComment,SearchTopic,ChangeTopikStatus,Updateurl


import string,random,functools
from config import sites,salt
from utils import from_base64,md5hash_create_salt



#########CONFIG APP#############################
class Bishop(Bottle):
    """
    Ovveride for statistic. Not work
    """
    def __call__( self, environ, start_response):
        return self.wsgi( environ, start_response)


app=Bottle()

def cookiesGen():
    let=string.ascii_letters
    cook=''
    while len(cook)<20:
        cook+=let[random.randint(0,51)]
    return cook

COOKIES_SECRET=cookiesGen()
if Platform=='win32':
    TEMPLATE_PATH.append('./template')
else: TEMPLATE_PATH.append(AppPath+'/template')



@app.route('/static/:path#.+#', name='static')
def static(path):
    if Platform=='win32':
        return static_file(path, root='static')
    return static_file(path, root=AppPath+'/static')



class BishopTemplate(SimpleTemplate):
    """Template engine without replace HTML special characters"""
    def bishop_html_escape(string):
        return string
    def prepare(self, escape_func=bishop_html_escape, noescape=False, **kwargs):
        self.cache = {}
        enc = self.encoding
        self._str = lambda x: bottle.touni(x, enc)
        self._escape = lambda x: escape_func(bottle.touni(x, enc))
        if noescape:
            self._str, self._escape = self._escape, self._str
Bview = functools.partial(view, template_adapter=BishopTemplate)


#COOKIES
def set_cookie(user):
    response.set_cookie(
        'account',
        user,
        secret=COOKIES_SECRET,
        max_age=7200
    )
    return

def del_cookie():
    response.set_cookie(
        'account',
        '',
        secret=COOKIES_SECRET,
        max_age=-1,
        expires=0
    )
    return

def get_cookies():
    username=request.get_cookie("account", secret=COOKIES_SECRET)
    return username


#Main routs
@app.route('/')
def index():
    name=get_cookies()
    if name:
        redirect('main')
    else:
        return template('index')

@app.route('/main')
@app.route('/main<text>')
@view('main')
def main(text=None):
    render={}
    username=get_cookies()
    if username:
        if text=='ch':
            render['msg']="Выборка сайтов совершена"
        if text=='cl':
            render['msg']="Выборка сайтов отменена"
        userid=GetIdUser(username)
        user_News=ChekNewsForLogin(userid)[0]
        i=1
        while i<=len(sites.keys()):
            if user_News[i]=='on':
                render[sites[str(i)]] ="checked"
            else:
                render[sites[str(i)]]=' '
            i+=1
        render['login']=username
        return render
    else:
        redirect('/')

@app.get('/chcontent')
def get_chcontent():
    redirect('/')

@app.post('/chcontent')
def chcontent():
    username=get_cookies()
    userid=GetIdUser(username)
    star={}
    sql_comm=''
    for i in sites.keys():
        k=request.forms.get(sites[i])
        star[sites[i]]=k
    for i in star.keys():
        sql_comm+=r" {0}='{1}', ".format(i,star[i],',')
    sql_comm=sql_comm[0:-2]
    SetNewsForLogin(sql_comm,userid)
    redirect('mainch')

@app.post('/clear')
def clear():
    username=get_cookies()
    if not username:
        redirect('/')
    userid=GetIdUser(username)
    sql_comm=''
    for i in sites.keys():
        sql_comm+=r" {0}='{1}', ".format(sites[i],'None',',')
    sql_comm=sql_comm[0:-2]
    SetNewsForLogin(sql_comm,userid)
    redirect('maincl')

#login/logout routs
@app.get('/login')
def login():
    username=get_cookies()
    if username:
        redirect('main')
    return template('login')

@app.post('/login')
def log_chek():
    account=request.forms.get('name')
    password=request.forms.get('password')
    password=md5hash_create_salt(password,salt)
    accept=Cheklogin(account,password)
    if accept:
        set_cookie(account)
        redirect('main')
    else:
        return template('login',err='Введенные данные не верны')

@app.get('/logout')
def logout():
    del_cookie()
    redirect('/')

#Registration routs
#----------------------------------------------
@app.get('/registr')
def show_registr():
    return template('registr')

@app.post('/registr')
def registration():
    account=request.forms.get('name')
    password=request.forms.get('password')
    password=md5hash_create_salt(password,salt)
    email=request.forms.get('email')
    if not account or not password or not email:
        return template('registr',err='Введены не все данные. Попробуйте снова.')
    account_valid=GetIdUser(account)
    if account_valid:
        return template('registr',err='Данный логин уже используется.')
    status=Registr_login(email,password,account)
    if status is True:
        set_cookie(account)
        return redirect('main')
    else:
        return template('registr', err='Ошибка. Повторите ввод данных.')


#Unsubscribe
@app.get('/unsubscribe_<hash_un>')
@Bview('content')
def unsubscribe(hash_un):
    user=from_base64(hash_un)[1]
    sql_comm=''
    for i in sites.keys():
        sql_comm+=r" {0}='{1}', ".format(sites[i],'None',',')
    sql_comm=sql_comm[0:-2]
    SetNewsForLogin(sql_comm,user)
    content="Рассылка ОТМЕНЕНА"
    return locals()


#CONTENT SIDE
@app.route('/content')
@app.route('/content<text>')
@Bview('content')
def contentnews(text=None):
    name=get_cookies()
    if name:
        login=name
    content="ELSE: В разработке"
    if text:
        content=GetContentPage(text)
        if not content:
            content="В разработке"
    return locals()

@app.route('/news')
@Bview('news')
def news():
    name=get_cookies()
    if name:
        login=name
    news=GetNewsOnsite()
    if len(news)>7:
        news=news[0:7]
    return locals()




#Administration.
@app.get('/duhastlider/command/<body>')
def adminajax(body):
    content=GetContentPage(body)
    return content

@app.post('/duhastlider/command/action/<page>')
def adminpost(page):
    text=request.forms.get('comment')
    SetContentPage(page,text)
    redirect ('/duhastlider')



@app.get('/duhastlider/news/<command>/<count>')
def newsajax(command,count):
    content=NewsControlerforAdmin(command,id=count)
    return content



@app.post('/duhastlider/news/<command>')
def newsadd(command):
    if command=="add":
        text=request.forms.get('text')
        if len(text)<5:
            redirect('/duhastlider')
        NewsControlerforAdmin('add',text)
        redirect('/duhastlider')
    if command=='change':
        text=request.forms.get('msg')
        id=request.forms.get('id')
        NewsControlerforAdmin('change',text,id)
        return
    redirect('/duhastlider')

@app.route('/duhastlider')
@view('admin')
def admin():
    return locals()


#bugreports

bootcolors={
    'open':{
        'type':'success',
        'text':'открыт'
    },
    'close':{
        'type':'danger',
        'text':'закрыт'
    },
    'inprogress':{
        'type':'warning',
        'text':'в работе'
    },
    'delay':{
        'type':'info',
        'text':'отложен'
    }
}

@app.route('/bugreport')
@view('bugreport')
def bugreport():
    name=get_cookies()
    if name:
        login=name
    bugreports=GetBugsTopics()
    return locals()


@app.post('/bugreport/<command>')
@view('bugreport')
def postbgreport(command):
    user=get_cookies()
    if user:
        login=user
    if command=='add':
        theme=request.forms.get('theme')
        text=request.forms.get('text')
        response=AddBugreport(user,text,theme)
        if not isinstance(response, text.__class__):
            response=str(response)
        data=request.files.data
        if data and data.file:
            path=AppPath+'/static/files/'
            filename=data.filename.replace(' ','_')
            fullfilename=path+response+'_'+filename
            raw=data.file.read()
            with open(fullfilename,'wb') as newfile:
                newfile.write(raw)
                Updateurl(response,response+'_'+filename)
        redirect('/bugreport')
    if command=='addcomment':
        comment=request.forms.get('comment').replace('\"','\'')
        comment=comment.replace("<p>", "<p class=\'text-left\' style=\'font-size: 16px\'> ")
        _id=request.forms.get('id')
        response=AddComment(_id,user,comment)
        redirect('/bugreport_'+str(_id))
    if command=='search':
        sql=''
        data=request.forms
        for item in data.items():
            if item[1]!='':
                sql+=item[0]+'='+"'"+item[1]+"'"+' or '
        sql=sql[:-4]
        if sql=="status='all'":
            sql=''
        bugreports=SearchTopic(sql)
        return locals()
    if command=="change_status":
        topik_id=request.forms.get('id')
        topik_status=request.forms.get('status')
        response=ChangeTopikStatus(topik_id,topik_status)
        if response:
            return 'ok'
        else:return 'error'




@app.get('/bugreport_<topik_id>')
#@view('bugtopick')
@Bview('bugtopick')
def getbugreport(topik_id):
    name=get_cookies()
    if name:
        login=name
    _id=topik_id
    response=GetTopicOfBugreport(_id)
    user,date,text,theme,status,url=response[0]
    if name:
        login=name
        if login==user:
            creator=bootcolors
    if url=='empty':
        del url
    _type=bootcolors[status]['type']
    statustext=bootcolors[status]['text']
    text=text.decode()
    comments=response[1]
    return locals()


@app.get('/test')
def test():
    return template('arcanoid')


#Server start.
run(app, server='tornado',host='127.0.0.1',port=8888, reloader=False)


